/**
 * 认证工具类
 * Authentication Utility Class
 */

class AuthManager {
  constructor() {
    this.user = null;
    this.token = localStorage.getItem('auth_token');
    this.init();
  }

  /**
   * 初始化认证状态
   */
  async init() {
    if (this.token) {
      try {
        await this.verifyToken();
      } catch (error) {
        console.warn('Token验证失败，清除本地存储');
        this.logout();
      }
    }
  }

  /**
   * 验证令牌
   */
  async verifyToken() {
    try {
      const response = await api.get('/auth/verify');
      if (response.success && response.user) {
        this.user = response.user;
        return true;
      } else {
        throw new Error('Token验证失败');
      }
    } catch (error) {
      console.error('Token验证失败:', error);
      throw error;
    }
  }

  /**
   * 用户登录
   */
  async login(email, password, rememberMe = false) {
    try {
      const response = await api.post('/auth/login', {
        email,
        password,
        rememberMe
      });

      if (response.success && response.token && response.user) {
        this.token = response.token;
        this.user = response.user;
        
        // 保存token到本地存储
        localStorage.setItem('auth_token', this.token);
        
        // 设置API客户端的token
        api.setToken(this.token);

        return response;
      } else {
        throw new Error(response.message || '登录失败');
      }
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  }

  /**
   * 用户登出
   */
  async logout() {
    try {
      if (this.token) {
        await api.post('/auth/logout');
      }
    } catch (error) {
      console.warn('登出请求失败，但继续清除本地状态');
    } finally {
      this.token = null;
      this.user = null;
      
      // 清除本地存储
      localStorage.removeItem('auth_token');
      
      api.setToken(null);
      
      // 跳转到登录页
      this.redirectToLogin();
    }
  }

  /**
   * 检查是否已登录
   */
  isAuthenticated() {
    return !!(this.token && this.user);
  }

  /**
   * 检查是否为管理员
   */
  isAdmin() {
    return this.user && this.user.role === 'admin';
  }

  /**
   * 获取当前用户信息
   */
  getCurrentUser() {
    return this.user;
  }

  /**
   * 跳转到登录页
   */
  redirectToLogin() {
    // 显示登录页，隐藏其他页面
    const loginPage = document.getElementById('login-page');
    const dashboardPage = document.getElementById('dashboard-page');
    
    if (loginPage) loginPage.classList.remove('hidden');
    if (dashboardPage) dashboardPage.classList.add('hidden');
  }

  /**
   * 跳转到仪表盘
   */
  redirectToDashboard() {
    // 隐藏登录页，显示仪表盘
    const loginPage = document.getElementById('login-page');
    const dashboardPage = document.getElementById('dashboard-page');
    
    if (loginPage) loginPage.classList.add('hidden');
    if (dashboardPage) dashboardPage.classList.remove('hidden');
  }

  /**
   * 更新用户信息
   */
  updateUser(userData) {
    if (this.user) {
      this.user = { ...this.user, ...userData };
    }
  }
}

// 创建全局认证管理器实例
window.auth = new AuthManager();